<?php


namespace app\blog\controller\v1;


use app\BaseController;
use app\blog\model\AdModel;
use app\blog\model\ArticleModel;
use app\blog\service\AdService;
use app\common\validate\IdMustIntValidate;
use think\facade\Db;

/**
 * 广告模块
 * Class Ad
 * @package app\blog\controller\v1
 */
class Ad extends BaseController
{
    /**
     * 获取推荐阅读
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommendedArticle(){
        $model = new ArticleModel();
        $result = $model->where('article_status', '=', 1)
            ->order('add_time', 'desc')
            ->visible(['id', 'article_title', 'article_synopsis'])
            ->limit(5)
            ->select()
            ->toArray();
        if ($result) {
            return successJson($result, "success");
        }
        return errorJson(60004, "error");
    }

    /**
     * 获取广告列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdList() {
        $model = new AdModel();
        $result = $model->where('status', '=', 1)
            ->order('px', 'asc')
            ->visible(['id', 'ad_image', 'ad_title', 'ad_url'])
            ->select();
        if ($result) {
            return successJson($result, "success");
        }
        return errorJson(60004, "error");
    }

    /**
     * 广告阅读量增加1
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function adOnClick() {
        $param = (new IdMustIntValidate())->validateParam();
        $ipTodayHas = (new AdService())->checkAdTodayHasIpInRedis($param['id'], $this->request->ip());
        if($ipTodayHas){
            $bool = Db::table('blog_admin_ad')
                ->where('id', '=', $param['id'])
                ->inc('ad_click_num')
                ->update();
            if($bool){
                return successJson(true);
            }
            return successJson(false);
        }
        return successJson(false);
    }
}